import React, { Component, useMemo } from 'react'
import { View } from '@tarojs/components'
import Taro, { getCurrentInstance } from '@tarojs/taro'
import { SpNavBar } from '@/components'
import api from '@/api'
import './index.scss'
import { connect } from 'react-redux'
import {
    Form,
    Input,
    Button,
    ImageUploader,
    Dialog,
    TextArea,
    DatePicker,
    CascadePicker,
    Cascader,
    Stepper,
    Switch,
    Checkbox,
    Space,
    Radio,
    Selector,
    Picker,
    Popup,
    SearchBar,
    CheckList
} from 'antd-mobile'
import {
    SHOP_MAP,
    SELECCAT_MAP,
    BRAND_MAP2,
    GOOD_MAP
} from '../../good/const'

export default class List extends Component {
    formRef = React.createRef()

    constructor(props) {
        super(props)
        this.state = {
            couponStr: '',
            items: [],
            shopItem: [],
            is_ziti: false,
            is_delivery: false,
            logo: [],
            banner: [],
            popVisible: false,
            defaultInfo: {},
            goodsList: [],
            merchantList: [],
            selectMerchant: [],
            operator_id: '',
        }
    }
    async componentWillUnmount() {
        console.log('2222')

    }
    // filteredItems = useMemo(() => {
    //     if (this.state.searchText) {
    //       return items.filter(item => item.includes(this.state.searchText))
    //     } else {
    //       return items
    //     }
    //   }, [items])
    async componentDidMount() {
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()

        await this.getMerchantList()
        if (!id) {
            this.setState({
                couponStr: '添加店铺管理员'
            })
        } else {
            this.setState({
                couponStr: '编辑店铺管理员',
                operator_id:id,
            })
            const info = Taro.getStorageSync('peopleManInfo')
            info.password = ''
            this.setState({
                defaultInfo: info
            })
            let list = this.getGood(info.distributor_ids)
            let lll = list.map((value) => {
                return value.value
            })
            this.state.shopItem = lll
             this.setState({
                // goodsList: list,
                shopItem: lll,
                selectMerchant: list,
            })
            this.formRef.current?.setFieldsValue(info)
            this.formRef.current?.setFieldsValue({ distributor_ids: lll })
        }
        // const info = Taro.getStorageSync('addressInfo')
        // this.formRef.current?.setFieldsValue(info)
    }

    async componentDidShow() {
        console.log('dianwu h5 comonentDidShow...')

    }
    async getMerchantList() {
        const data = await api.shop.getShopList({
            is_valid: true,
            pageSize: 1000
        })
        console.log(data)
        this.setState({
            merchantList: [...data.list]
        })
    }
    onSubmit = async () => {
        const values = this.formRef.current?.getFieldsValue()
        Dialog.alert({
            content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        })
        let params = {
            ...JSON.parse(JSON.stringify(values)),
        }
        let arr = this.state.merchantList.filter((item) => {
            // return item.distributor_id == val[0]
            return params.distributor_ids.includes(item.distributor_id)
        })
        console.log(arr)
        params.distributor_ids = arr
        params.operator_type = 'distributor'
        params.isHead = 'false'
        console.log(params)
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        if (!id) {
            await api.shop.postPeopleManagement(params)
        } else {
            if(params.password.length <=0){
                delete params.password
                // delete params.distributor_id/s
            }
            params.operator_id = this.state.operator_id
            await api.shop.updatePeopleManagement(params)
        }


        Taro.navigateBack()
    }
    onFinish = (values) => {
        console.log(values)
        if (values.quantity) {

        }
        this.onSubmit(values)
    }
    onFinishFailed = (values) => {
        Dialog.alert({
            content: <pre>{JSON.stringify(values, null, 2)}</pre>,
        })
    }
    onClickGoogs = async (values) => {
        console.log('index-294打印values', values)
        let list = this.getGood(values)
        console.log('index-294打印values', list)
        let lll = list.map((value) => {
            return value.value
        })
        this.state.shopItem = lll
         this.setState({
            // goodsList: list,
            shopItem: lll,
            selectMerchant: list,
            form: this.state.form
        })

        // params.items = lll
        this.formRef.current?.setFieldsValue({ distributor_ids: lll })
    }
    getGood(value) {
        let list = this.transformData(value, SHOP_MAP)
        return list
    }
    transformData(data, obj) {
        let list = []
        data.forEach((item) => {
            let currentItem = {}
            for (let key in obj) {
                currentItem[obj[key]] = item[key]
            }
            if (item.children) {
                currentItem.children = transformData(item.children, obj)
            }
            list.push(currentItem)
        })
        return list
    }
    render() {
        const form = this.state.form
        const {
            router: {
                params: { id }
            }
        } = getCurrentInstance()
        return (
            <View className='creat-form'>
                <SpNavBar title={this.state.couponStr} />
                <Form
                    ref={this.formRef}
                    layout='horizontal'
                    footer={
                        <Button block type='submit' color='primary' size='large' >
                            提交
                        </Button>
                    }
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    initialValues={{}}
                >

                    <Form.Item
                        name='login_name'
                        label='登录账号'
                        rules={[{
                            required: true,
                            message: '登录账号',
                        }]}
                    >
                        <Input readOnly={this.state.operator_id.length>0} onChange={console.log} placeholder='登录账号' />
                    </Form.Item>
                    <Form.Item
                        name='mobile'
                        label='手机号'
                        rules={[{
                            required: true,
                            message: '手机号',
                            // pattern: '(^1[3-9]\\d{9}$)'
                        }]}
                    >
                        <Input onChange={console.log} placeholder='请输入手机号' />
                    </Form.Item>
                    <Form.Item
                        name='username'
                        label='姓名'
                        rules={[{
                            required: true,
                            message: '姓名',
                        }]}
                    >
                        <Input onChange={console.log} placeholder='请输入姓名' />
                    </Form.Item>
                    {this.state.operator_id.length >0 ?(<Form.Item label='登录密码' name='password'
                      
                    >
                        <Input type='password' placeholder='请输入密码' />
                    </Form.Item>):(<Form.Item label='登录密码' name='password'
                        rules={[{
                            required: true,
                            message: '登录密码',
                        }]}
                    >
                        <Input type='password' placeholder='请输入密码' />
                    </Form.Item>)}
                    <Form.Item label="所属店铺" name='distributor_ids'
                        trigger='onConfirm'
                        rules={[{ required: true, message: '店铺不能为空' }]}
                        onClick={(e) => {
                            this.setState({
                                popVisible: true
                            })
                        }}
                    >
                        <Selector
                            columns={2}
                            multiple
                            options={this.state.selectMerchant}
                            disabled
                        />
                    </Form.Item>
                </Form>
                <Popup
                    className='select-popup'
                    visible={this.state.popVisible}
                    onMaskClick={() => {
                        this.setState({ popVisible: false })
                    }}
                    destroyOnClose

                >
                    <div className='rigth-btn' onClick={() => {
                        this.setState({
                            popVisible: false,
                        })
                    }}>
                        确定
                    </div>
                    <div>
                        <CheckList
                            multiple
                            className='select-popup-checkList'
                            defaultValue={this.state.shopItem}
                            // value={this.state.shopItem}
                            onChange={async (val) => {
                                let arr = this.state.merchantList.filter((item) => {
                                    // return item.distributor_id == val[0]
                                    return val.includes(item.distributor_id)
                                })
                                console.log(arr)
                                this.onClickGoogs(arr)

                            }}
                        >
                            {this.state.merchantList.map(item => (
                                <CheckList.Item key={item.distributor_id} value={item.distributor_id}>
                                    {item.name}
                                </CheckList.Item>
                            ))}
                        </CheckList>
                    </div>
                </Popup>
            </View >

        )
    }
}
